package jgl.vajra.management.widget.retrofithelper.interceptor;

import android.text.TextUtils;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by Mloong on 2018/8/2.
 */

public class CacheOnlineInterceptor implements Interceptor {
    private int maxCacheTimeSecond = 0;

    public CacheOnlineInterceptor(int maxCacheTimeSecond) {
        this.maxCacheTimeSecond = maxCacheTimeSecond;
    }

    public CacheOnlineInterceptor() {
        this.maxCacheTimeSecond = 10;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        String cache = chain.request().header("locationCache");
        if (!TextUtils.isEmpty(cache)) {
            maxCacheTimeSecond = Integer.parseInt(cache);
        } else {
            maxCacheTimeSecond = 5;
        }

        Response response = chain.proceed(request);
        return response.newBuilder()
                .removeHeader("Pragma")// 清除头信息，因为服务器如果不支持，会返回一些干扰信息，不清除下面无法生效
                .removeHeader("Cache-Control")
                .header("Cache-Control", "public, max-age=" + maxCacheTimeSecond)
                .build();

    }

}
